package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.PingAnService;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.StringUtil;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwThirdback;
import com.meirengu.webview.service.KwThirdbackService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 平安相关接口（平安惠普、平安人寿）
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class PingAnServiceImpl implements PingAnService {

    Logger logger = LoggerFactory.getLogger(PingAnServiceImpl.class);

    @Autowired
    KwThirdbackService kwThirdbackService;

    /**
     * 平安普惠接口
     *
     * @param name     姓名
     * @param gender   性别  1.男 2.女
     * @param mobile   手机号
     * @param birthday 出生日期 格式：1990-01-02
     */
    public Integer puhuiAdd(String name, String gender, String mobile, String birthday, String income,
                            String payroll, String car, String lifeInsuranceTotal, String profession,
                            String injob, String houseLoan, String carLoad, String card, String lifeInsurance,
                            String loanMoney, String loanDeadline, String bankLoan, String funds, String jinpo,
                            String housePledge, String house, String extentedParam) {

        String url = ConfigUtil.getConfig("pingan.puhui.add.url");
        String debug = ConfigUtil.getConfig("pingan.puhui.add.debug");
        //String url = "http://api.datasuv.net/data/add?m=M18yXzI1NV8xODY=";
        Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("gender", gender);
        params.put("mobile", mobile);
        params.put("birthday", birthday);
        if (!StringUtil.isEmpty(income)) {
            params.put("income", income);
        }
        if (!StringUtil.isEmpty(payroll)) {
            params.put("payroll", payroll);
        }
        if (!StringUtil.isEmpty(car)) {
            params.put("car", car);
        }
        if (!StringUtil.isEmpty(lifeInsuranceTotal)) {
            params.put("life_insuranceTotal", lifeInsuranceTotal);
        }
        if (!StringUtil.isEmpty(profession)) {
            params.put("profession", profession);
        }
        if (!StringUtil.isEmpty(injob)) {
            params.put("injob", injob);
        }
        if (!StringUtil.isEmpty(houseLoan)) {
            params.put("house_loan", houseLoan);
        }
        if (!StringUtil.isEmpty(carLoad)) {
            params.put("car_loan", carLoad);
        }
        if (!StringUtil.isEmpty(card)) {
            params.put("card", card);
        }
        if (!StringUtil.isEmpty(lifeInsurance)) {
            params.put("life_insurance", lifeInsurance);
        }
        if (!StringUtil.isEmpty(loanMoney)) {
            params.put("loan_money", loanMoney);
        }
        if (!StringUtil.isEmpty(loanDeadline)) {
            params.put("loan_deadline", loanDeadline);
        }
        if (!StringUtil.isEmpty(bankLoan)) {
            params.put("bank_loan", bankLoan);
        }
        if (!StringUtil.isEmpty(funds)) {
            params.put("funds", funds);
        }
        if (!StringUtil.isEmpty(jinpo)) {
            params.put("jinpo", jinpo);
        }
        if (!StringUtil.isEmpty(housePledge)) {
            params.put("house_pledge", housePledge);
        }
        if (!StringUtil.isEmpty(house)) {
            params.put("house", house);
        }
        if (!StringUtil.isEmpty(extentedParam)) {
            params.put("extentedParam", extentedParam);
        }


        if (!StringUtil.isEmpty(debug)) {
            params.put("debug", debug);
        }
        KwThirdback thirdback = new KwThirdback();
        thirdback.setInterfaceCode("pinganph");
        thirdback.setInterfaceName("平安普惠");
        thirdback.setMobile(mobile);
        thirdback.setSendUrl(url.toString());
        thirdback.setParams(params.toString());
        thirdback.setCode(Constants.BUSINESS_STATUS_FAIL);
        /**
         * 返回成功示例：{"msg":"添加成功","status":"success","data":{"pingan_code":"","policy_no":""}}
         */
        try {
            HttpUtil.HttpResult hr = HttpUtil.doPostForm(url, params);
            thirdback.setBackUrl(hr.toString());
            thirdback.setHttpCode(hr.getStatusCode());
            thirdback.setHttpContent(hr.getContent());
            int code = hr.getStatusCode();
            if (code == 200) {
                logger.info("==PingAnServiceImpl.puhuiAdd http requesst success. result:{}", code, hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String status = returnMsg.getString("status");
                if ("success".equals(status)) {
                    thirdback.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    thirdback.setMessage("成功");
                    logger.info("==PingAnServiceImpl.puhuiAdd add success");
                } else {
                    thirdback.setCode(Constants.BUSINESS_STATUS_FAIL);
                    thirdback.setMessage(returnMsg.getString("msg"));
                    logger.warn("==PingAnServiceImpl.puhuiAdd add fail");
                }
            } else {
                logger.warn("==PingAnServiceImpl.puhuiAdd http requesst fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            thirdback.setHttpCode(408);
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwThirdbackService.insert(thirdback);
            return thirdback.getCode();
        }

    }

    /**
     * 平安人寿接口
     *
     * @param name     姓名
     * @param gender   性别  1.男 2.女
     * @param mobile   手机号
     * @param birthday 出生日期 格式：1990-01-02
     */
    public Integer renshouAdd(String name, String gender, String mobile, String birthday, String ip, String carType, String houseType) {
        String url = ConfigUtil.getConfig("pingan.renshou.add.url");
        String debug = ConfigUtil.getConfig("pingan.renshou.add.debug");
        //String url = "http://api.datasuv.net/data/add?m=M18yXzI1NV8xODY=";
        Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("gender", gender);
        params.put("mobile", mobile);
        params.put("birthday", birthday);
        if (!StringUtil.isEmpty(debug)) {
            params.put("debug", debug);
        }
        //扩展字段
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("carType", carType);
        jsonObject.put("houseType", houseType);
        jsonObject.put("client_ip", ip);
        params.put("extentedParam", "[" + jsonObject.toString() + "]");

        KwThirdback thirdback = new KwThirdback();
        thirdback.setInterfaceCode("pinganzx");
        thirdback.setInterfaceName("平安赠险");
        thirdback.setMobile(mobile);
        thirdback.setSendUrl(url.toString());
        thirdback.setParams(params.toString());
        /**
         * 返回成功示例：{"msg":"添加成功","status":"success","data":{"pingan_code":"","policy_no":""}}
         */
        try {
            HttpUtil.HttpResult hr = HttpUtil.doPostForm(url, params);
            thirdback.setBackUrl(hr.toString());
            thirdback.setHttpCode(hr.getStatusCode());
            thirdback.setHttpContent(hr.getContent());
            int code = hr.getStatusCode();
            if (code == 200) {
                logger.info("==PingAnServiceImpl.renshouAdd http requesst success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String status = returnMsg.getString("status");
                if ("success".equals(status)) {
                    thirdback.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    thirdback.setMessage("成功");
                    logger.info("==PingAnServiceImpl.renshouAdd add success");
                } else {
                    thirdback.setCode(Constants.BUSINESS_STATUS_FAIL);
                    thirdback.setMessage(returnMsg.getString("msg"));
                    logger.warn("==PingAnServiceImpl.renshouAdd add fail");
                }
            } else {
                thirdback.setHttpCode(code);
                logger.warn("==PingAnServiceImpl.renshouAdd http requesst fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            thirdback.setHttpCode(408);
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwThirdbackService.insert(thirdback);
            return thirdback.getCode();
        }


    }

    public static void main(String[] args) {
        PingAnServiceImpl p = new PingAnServiceImpl();
//        p.renshouAdd("张Mao","1","18813099929","1989-10-19");
    }
}
